<!--
  -    Copyright (c) 2018-2025, hycloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: hycloud
  -->
<template>
    <div class="execution">
        <basic-container>
            <avue-crud ref="crud"
                         v-model="form"
                       :page.sync="page"
                       :data="tableData"
                       :permission="permissionList"
                       :table-loading="tableLoading"
                       :option="tableOption"
                       @on-load="getList"
                       @search-change="searchChange"
                       @refresh-change="refreshChange"
                       @size-change="sizeChange"
                       @current-change="currentChange">
                       <template slot="attachment"  slot-scope="scope">
                            <div v-for="(item,index) in JSON.parse(scope.row.attachment)" :key="index" class="underline-block">
                                <a :href="item.url" :download="item.original">{{item.original}}</a>
                            </div>
                        </template>
                       <template slot="menuLeft">
                            <el-button
                            icon="el-icon-circle-plus"
                            size="small"
                            type="primary"
                            @click="openDialogform">新增</el-button>
                        </template>
                       <template slot="menu" slot-scope="scope">
                           <el-button type="text"
                                icon="el-icon-circle-view"
                                size="small"
                                @click="view(scope)">查看</el-button>
                            <el-button type="text"
                                icon="el-icon-circle-view"
                                size="small"
                                v-if="scope.row.status === '0'"
                                @click="cancel(scope)">取消</el-button>
                            <el-button type="text"
                                icon="el-icon-circle-view"
                                size="small"
                                v-if="scope.row.status === '0'"
                                @click="send(scope)">出车</el-button>
                            <el-button type="text"
                                icon="el-icon-circle-edit"
                                size="small"
                                @click="back(scope)" v-if="scope.row.status === '1'">返程登记</el-button>
                        </template>
            </avue-crud>
        </basic-container>
        <el-dialog
            :visible.sync="modal"
            v-if="modal"
            :title="title"
            width="1200px"
            @close="closeDialog"
            top="5vh"
            :close-on-click-modal="false"
            append-to-body>
            <div class="ck-designer">
                <el-form ref="form" :rules="rules" :model="form" label-width="100px">
                    <el-row>
                        <el-col :span="12">
                             <el-form-item label="用车人" prop="applyUsername">
                                <el-input v-model="form.applyUsername" :disabled="true" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                             <el-form-item label="出车地点" prop="address">
                                 <el-select v-model="form.address"
                                            placeholder="请选择出车地点"
                                            :disabled="title == '派车单详情'"
                                            clearable>
                                    <el-option v-for="item in optionsAd"
                                            :key="item.id"
                                            :label="item.label"
                                            :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="form.address === '其他'">
                        <el-col :span="24">
                             <el-form-item label="其他地点" prop="others_address">
                                <el-input v-model="form.others_address" :maxlength="128" :disabled="title == '派车单详情'" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="标题" prop="bizTitle">
                            <el-input v-model="form.bizTitle" :disabled="title == '派车单详情'"></el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item  prop="withMember">
                            <label for="withMember" class="red-star" slot="label">同乘人员</label>
                            <el-input  placeholder="请选择人员" v-model="withMember_str"  @focus="choseMember" :disabled="title == '派车单详情'">
                                <el-button slot="append" @click="choseMember" :disabled="title == '派车单详情'">选择</el-button>
                            </el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="车辆型号" prop="carModel">
                                <el-select v-model="form.carModel"
                                            placeholder="请选择车辆型号"
                                            @change="changeMo"
                                            :disabled="title == '派车单详情'"
                                            clearable>
                                    <el-option v-for="item in optionsMo"
                                            :key="item.id"
                                            :label="item.label"
                                            :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                             <el-form-item label="车牌" prop="carNo">
                                 <el-select v-model="form.carNo"
                                            placeholder="请选择车牌"
                                            :disabled="title == '派车单详情'"
                                            clearable>
                                    <el-option v-for="item in optionsNo1"
                                            :key="item.carNo"
                                            :label="item.carNo"
                                            :value="item.carNo">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="司机" prop="driverId">
                                <el-select v-model="form.driverId"
                                            placeholder="请选择司机"
                                            :disabled="title == '派车单详情'"
                                            clearable>
                                    <el-option v-for="item in optionsDr"
                                            :key="item.driverId"
                                            :label="item.driverName"
                                            :value="item.driverId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                             <el-form-item label="使用时间" prop="dateRange">
                                <el-date-picker
                                    v-model="form.dateRange"
                                    @change="changeDate"
                                    :disabled="title == '派车单详情'"
                                    type="datetimerange"
                                    range-separator="至"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    format="yyyy年MM月dd日 HH:mm:ss"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="外出地点" prop="outAddress">
                            <!-- <el-input type="textarea" placeholder="请输入外出地点(广州市五区内用车(5人及以上)，广州市五区外(3人及以上))" v-model="form.outAddress" :disabled="title == '派车单详情'"></el-input> -->
                            <el-select v-model="form.outAddress"
                                        placeholder="广州市五区内同乘人员必须大于等于4个，五区外同乘人员必须大于等于2个"
                                        :disabled="title == '派车单详情'"
                                        clearable>
                                <el-option 
                                    label="广州市5区内" 
                                    value="广州市5区内">
                                </el-option>
                                <el-option 
                                    label="广州市5区外" 
                                    value="广州市5区外">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="出车事由" prop="reason">
                            <el-input type="textarea" placeholder="请输入出车事由（注明目的地）" :disabled="title == '派车单详情'" v-model="form.reason"></el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="说明">
                            <el-input type="textarea" :disabled="title == '派车单详情'" v-model="form.remark" :rows="4" :maxlength="512"></el-input>
                        </el-form-item>
                    </el-row>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="alarmHandle('form')">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :visible.sync="modal1"
            v-if="modal1"
            title="返程登记"
            width="1300px"
            @close="closeDialog1"
            top="5vh"
            :close-on-click-modal="false"
            append-to-body>
            <div class="ck-designer">
                <el-form ref="form1" :rules="rules1" :model="form1" label-width="100px">
                    <el-row>
                        <el-col :span="12">
                             <el-form-item label="里程" prop="km">
                                <el-input-number v-model="form1.km" :min="0" :max="1000000" clearable></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                             <el-form-item label="费用" prop="fee">
                                 <el-input-number v-model="form1.fee" :min="0" :max="1000000" clearable></el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                             <el-form-item label="使用时间" prop="dateRange">
                                <el-date-picker
                                    v-model="form1.dateRange"
                                    @change="changeDate1"
                                    type="datetimerange"
                                    range-separator="至"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    format="yyyy年MM月dd日 HH:mm:ss"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="说明">
                            <el-input type="textarea" v-model="form1.remark" :maxlength="512"></el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="附件">
                            <el-upload
                                class="upload-demo"
                                :headers="headers"
                                action="/act/file/upload"
                                :on-success="handleSuccess"
                                :on-preview="download"
                                :on-remove="handleRemove"
                                multiple
                                :file-list="fileList">
                                <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <!-- <avue-form ref="form1" :option="option" v-model="obj">
                            <template slot="menuLeft">
                                <el-button @click="addRow" size="small">新增</el-button>
                            </template>
                        </avue-form> -->
                        <avue-form :option="option" v-model="obj">
                        </avue-form>
                    </el-row>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog1">取 消</el-button>
                <el-button type="primary" @click="alarmHandle1('form1')">确 定</el-button>
            </span>
        </el-dialog>
        <choose-member v-if="showChose" :labelkey="labelkey" :url1="url1" :url2="url2" :title="title1" :columns1="columns1" :columns="columns" :type="type" :flKey="flKey"></choose-member>
    </div>
</template>

<script>
    import {fetchList, back, cancel, send} from '@/api/car/cardispatchbill'
    import {addObj} from '@/api/car/oacarbill'
    import {getObjForm} from '@/api/activiti/oaconfig'
    import {fetchList as fetchcarList} from '@/api/car/car'
    import {fetchList as fetchdrList} from '@/api/car/cardriver'
    import { remote } from "@/api/admin/dict";
    import chooseMember from '@/components/chooseMember'
    import eventBus from '@/util/eventBus'
    import _ from 'lodash'
    import {tableOption} from '@/const/crud/car/cardispatchbill'
    import {mapGetters} from 'vuex'
    import store from '@/store'

    export default {
        name: 'cardispatchbill',
        components: { chooseMember },
        data() {
            return {
                obj: {
                    dynamic: []
                },
               option: {
                    labelWidth: 0,
                    submitBtn: false,
                    emptyBtn:false,
                    column: [
                    {
                        label: '',
                        prop: 'dynamic',
                        type: 'dynamic',
                        span:24,
                        children: {
                        align: 'center',
                        headerAlign: 'center',
                        rowAdd:(done)=>{
                            done()
                        },
                        rowDel:(row,done)=>{
                            done()
                        },
                       column: [
                            {
                                "type": "select",
                                "label": "费用类别",
                                "prop": "type",
                                "span": 12,
                                width: 165,
                                cell: true,
                                dicUrl: "/admin/dict/type/car_fee_type",
                                rules: [{
                                    required: true,
                                    message: '请选择费用类别',
                                    trigger: 'blur'
                                }],
                            },
                            {
                                "type": "input",
                                "label": "费用名称",
                                "prop": "name",
                                width: 165,
                                "span": 12,
                                cell: true,
                                maxlength: 120,
                                rules: [{
                                    required: true,
                                    message: '请填写费用名称',
                                    trigger: 'blur'
                                }],
                            },
                            {
                                "type": "date",
                                "label": "费用发生时间",
                                "prop": "feeTime",
                                cell: true,
                                "span": 12,
                                format: 'yyyy-MM-dd',
                                valueFormat: 'yyyy-MM-dd',
                            },
                            {
                                "type": "number",
                                "label": "金额",
                                "prop": "fee",
                                width: 165,
                                cell: true,
                                "span": 12,
                                maxRows: 1000000,
                                minRows:0,
                                value: 0,
                                rules: [{
                                    required: true,
                                    message: '请填写金额',
                                    trigger: 'blur'
                                }],
                            },	  {
                                "type": "select",
                                "label": "发票类型",
                                cell: true,
                                width: 165,
                                "prop": "invoiceType",
                                "span": 12,
                                dicUrl: "/admin/dict/type/invoice_type",
                                rules: [{
                                    required: true,
                                    message: '请选择发票类型',
                                }],
                            },	  {
                                "type": "number",
                                "label": "发票张数",
                                cell: true,
                                width: 165,
                                "prop": "invoiceNumber",
                                "span": 12,
                                maxRows: 1000000,
                                minRows:0,      
                                value: 0,
                                },	  {
                                "type": "number",
                                "label": "发票金额",
                                width: 165,
                                cell: true,
                                "prop": "invoiceFee",
                                "span": 12,
                                maxRows: 1000000,
                                minRows:0,
                                value: 0,
                            }
                        ]
                        }
                    }]
                },
                form: {},
                // headers: {
                //     Authorization: 'Bearer ' + store.getters.access_token
                // },
                title: '新增派车单',
                fileList: [],
                flKey: 'categoryId',
                url1: '',
                url2: '',
                type:'',
                columns:[],
                columns1:[],
                title1: '',
                withMember_str: '',
                labelkey: '',
                showChose: false,
                modal: false,
                modal1: false,
                form:{
                    carNo: ''
                },
                form1:{},
                optionsAd: [],
                optionsMo: [],
                optionsNo: [],
                optionsNo1: [],
                optionsDr: [],
                optionsDr1: [],
                optionsDr2: [],
                data: [],
                rules: {
                    bizTitle: [
                        { required: true, message: '请输入标题', trigger: 'blur' },
                        { min: 1, max: 128, message: '长度在 1 到 128 个字符', trigger: 'blur' }
                    ],
                    address: [
                        { required: true, message: '请选择出车地点' }
                    ],
                    dateRange: [
                        { required: true, message: '请选择使用时间' }
                    ],
                    carModel: [
                        { required: true, message: '请选择车辆型号' }
                    ],
                    outAddress: [
                        { required: true, message: '请输入外出地点', trigger: 'blur' },
                        { min: 1, max: 128, message: '长度在 1 到 128 个字符', trigger: 'blur' }
                    ],
                    driverId: [
                        { required: true, message: '请选择司机' }
                    ],
                    carNo: [
                        { required: true, message: '请选择车牌' }
                    ],
                    reason: [
                        { required: true, message: '请输入出车事由', trigger: 'blur' },
                        { min: 1, max: 512, message: '长度在 1 到 512 个字符', trigger: 'blur' }
                    ],
                },
                rules1: {
                    // km: [
                    //     { required: true, message: '请输入里程', trigger: 'blur' }
                    // ],
                    // fee: [
                    //     { required: true, message: '请输入费用', trigger: 'blur' }
                    // ],
                    // dateRange: [
                    //     { required: true, message: '请选择使用时间' }
                    // ]
                },
                searchForm: {},
                tableData: [],
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                tableLoading: false,
                tableOption: tableOption
            }
        },
        computed: {
            ...mapGetters(['permissions']),
            headers() {
                return {
                    Authorization: "Bearer " + store.getters.access_token
                }
            },
            permissionList() {
                return {
                    addBtn: false,
                    delBtn: false,
                    editBtn: false
                };
            }
        },
        created() {
            this.init()
            this.eventBusHandle()
        },
        methods: {
            init() {
                fetchcarList({status: 1, dispatchStatus: 0}).then(response => {
                    this.optionsNo = response.data.data.records
                })
                fetchdrList({status: 1, dispatchStatus: 0}).then(response => {
                    this.optionsDr1 = response.data.data.records
                })
                fetchdrList({size: -1}).then(response => {
                    this.optionsDr2 = response.data.data.records
                })
                remote('car_model').then(response => {
                    this.optionsMo = response.data.data
                })
                remote('car_use_area').then(response => {
                    this.optionsAd = response.data.data
                })
            },
            addRow() {
                this.$refs.crud1.rowCellAdd( {
                    id: Math.random(),
                });
            },
            openDialogform() {
                this.form = {
                    carNo: ''
                }
                this.optionsDr = this.optionsDr1
                this.title = '新增派车单'
                this.form.applyUsername = _.get(this, '$store.getters.userInfo.realname')
                this.modal = true
            },
            view(scope) {
                this.title = '派车单详情'
                this.optionsDr = this.optionsDr2
                this.form = scope.row
                this.form.applyUsername = _.get(this, '$store.getters.userInfo.realname')
                let chosead = this.optionsAd.filter(item => {
                    return item.value === this.form.address
                })
                if (this.form.address && chosead.length === 0) {
                    this.form.others_address = this.form.address
                    this.form.address = '其他'
                }
                if(this.form.useBeginTime && this.form.useEndTime) {
                    this.form.dateRange = [this.form.useBeginTime, this.form.useEndTime]
                }
                if(this.form.withMember) {
                    let memberList = JSON.parse(this.form.withMember)
                    let namelist = []
                    if (memberList.length > 0) {
                        memberList.map(item => {
                            namelist.push(item.realname)
                        })
                    }
                    this.withMember_str = namelist.join()
                }
                this.modal = true
            },
            eventBusHandle () {
                let _this = this
                eventBus.$on('getMember', function (data) {
                    _this.form.withMember = JSON.stringify(data.withMember)
                    _this.withMember_str = data.withMember_choose_member
                })
            },
            download(file) {
                const win = window.open(file.response.data.url)
                win.opener = null
            },
            handleSuccess(response, file, fileList) {
                let att = []
                if (fileList.length) {
                    fileList.map(item => {
                        att.push({
                            original: item.response.data.original,
                            url: item.response.data.url,
                        })
                    })
                    this.form1.attachment = JSON.stringify(att)
                } else {
                    this.form1.attachment = ''
                }
            },
            handleRemove(file, fileList) {
                let att = []
                if (fileList.length) {
                    fileList.map(item => {
                        att.push({
                            original: item.response.data.original,
                            url: item.response.data.url,
                        })
                    })
                    this.form1.attachment = JSON.stringify(att)
                } else {
                    this.form1.attachment = ''
                }
            },
            changeMo(value) {
                this.form.carNo = ''
                if (value) {
                    this.optionsNo1 = this.optionsNo.filter(item => {
                        return item.carModel === value
                    })
                } else {
                    this.optionsNo1 = Object.assign([], this.optionsNo)
                }
            },
            choseMember () {
                this.type = "checkbox"
                this.labelkey = 'withMember_choose_member'
                this.url1 = '/admin/dept/tree'
                this.url2 = '/admin/user/page/simple'
                this.title1 = '组织机构'
                this.flKey = 'deptId'
                this.columns = [
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username',
                },
                {
                    title: '姓名',
                    key: 'realname',
                    dataIndex: 'realname',
                },
                {
                    title: '所属部门',
                    dataIndex: 'deptId',
                    key:'deptId',
                    scopedSlots: { customRender: 'deptId' },
                },
                {
                    title: '岗位',
                    dataIndex: 'post',
                    key: 'post',
                    scopedSlots: { customRender: 'post' }
                }
                ]
                this.columns1 = [
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username' 
                },
                {
                    title: '操作',
                    key: 'action',
                    scopedSlots: { customRender: 'action' },
                },
                ]
                this.showChose = true
            },
            changeDate(value) {
                this.form.useBeginTime = value[0]
                this.form.useEndTime = value[1]
            },
            changeDate1(value) {
                this.form1.startTime = value[0]
                this.form1.endTime = value[1]
            },
            closeDialog() {
                this.modal = false
                this.form = {}
                this.withMember_str = ''
            },
            closeDialog1() {
                this.modal1 = false
                this.form1 = {}
            },
            alarmHandle(formName) {
                let _this = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (!this.form.withMember || this.form.withMember.length  === 0) {
                            this.$message.error('请选择同乘人员')
                            return
                        }
                        let form2 = Object.assign({}, _this.form)
                        if (_this.form.address === '其他') {
                            if (!_this.form.others_address) {
                                this.$message.error('请填写其他出车地点')
                                return
                            }
                            form2.address = form2.others_address
                        }
                        addObj(form2).then(data => {
                            this.$message.success('添加成功')
                            this.getList(this.page)
                            this.init()
                            this.closeDialog()
                        })
                    }
                })
            },
            alarmHandle1(formName) {
                let _this = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let validFlag = true
                        if(_this.obj.dynamic.length > 0) {
                            _this.obj.dynamic.map(item => {
                                if (!item.type) {
                                    this.$message.error('请选择费用类别')
                                    validFlag = false
                                    return
                                } else if(!item.name) {
                                    this.$message.error('请填写费用名称')
                                    validFlag = false
                                    return
                                } else if(!item.fee && item.fee !== 0) {
                                    this.$message.error('请填写金额')
                                    validFlag = false
                                    return
                                } else if(!item.invoiceType) {
                                    this.$message.error('请选择发票类型')
                                    validFlag = false
                                    return
                                }
                            })
                        }
                        if (validFlag) {
                            _this.form1.carFeeList = _this.obj.dynamic
                            back(_this.form1).then(response => {
                                this.$message.success('登记成功')
                                this.getList(this.page)
                                this.init()
                                this.closeDialog1()
                            })
                        }
                    }
                })
            },
            back(scope) {
                this.form1 = {}
                this.obj.dynamic = []
                this.modal1 = true
                this.form1.dispatchId = scope.row.dispatchId
            },
            cancel(data) {
                this.$prompt('请输入说明', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern:/^(?=[\s\S]{0,20}$)/,
                    inputErrorMessage: '请不要输入超过20字符'
                }).then(({ value }) => {
                    cancel({dispatchId:data.row.dispatchId, remark: value}).then(response => {
                        this.$message.success('取消成功')
                        this.init()
                        this.getList(this.page)
                    })
                })
            },
            send(data) {
                this.$prompt('请输入说明', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(({ value }) => {
                    send({dispatchId:data.row.dispatchId, remark: value}).then(response => {
                        this.$message.success('派车成功')
                        this.init()
                        this.getList(this.page)
                    })
                })
            },
            getList(page, params) {
                this.tableLoading = true
                if (this.searchForm.dateRange) {
                    this.searchForm.startDate = this.searchForm.dateRange[0];
                    this.searchForm.endDate = this.searchForm.dateRange[1];
                }
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params, this.searchForm )).then(response => {
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading=false
                })
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize
            },
            currentChange(current){
                this.page.currentPage = current
            },
            searchChange(form, done) {
                this.searchForm = form
                this.page.currentPage = 1
                this.getList(this.page, form)
                done()
            },
            refreshChange() {
                this.getList(this.page)
            }
        }
    }
</script>
<style scoped  lang="scss">
/deep/.el-select, .el-input-number, .el-date-editor{
    width: 100%;
}
.red-star:before{
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
}
</style>